package cn.t.modules.scheduler.core.config;

import cn.t.modules.timewheel.core.hierarchical.TTaskScheduler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

/**
 * @author 陶敏麒
 * @date 2024/3/5 14:11
 */
@EnableAsync
@EnableScheduling
@Configuration
public class SchedulerConfig implements SchedulingConfigurer, AsyncConfigurer {

    /**
     * 线程池名称
     */
    public static final String TASK_POOL_NAME = "SCHEDULE-POOL";

    /**
     * 配置线程池执行器<br>
     * 重写了这个方法后,定时任务会自动从线程池中获取线程
     * @param taskRegistrar 注册器
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(this.taskExecutor());
    }

    @Bean
    public TTaskScheduler taskScheduler() {
        var scheduler = new TTaskScheduler();
        scheduler.start();
        return scheduler;
    }

    /**
     * 配置定时任务线程池<br>
     * @return 线程池
     */
    @Bean(TASK_POOL_NAME)
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler ();
        // 设置线程容量
        executor.setPoolSize(10);
        // 设置默认线程名称
        executor.setThreadNamePrefix("schedule-");
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        return executor;
    }
}
